package JDBC;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;

import com.google.protobuf.compiler.PluginProtos;
import com.sun.net.httpserver.HttpServer;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

/**
 * DBCP配置类
 * @author 王逸润
 * 备注:直接使用该连接池可能出错，需要在本地数据库运行：
 * SET GLOBAL time_zone ='+8:00';
 * SET time_zone = '+8:00';
 * FLUSH PRIVILEGES;
 */
public class KCYDBCPUtil {

    private static Properties properties = new Properties();
    private static DataSource dataSource;

    //加载DBCP配置文件
    static
    {
        try{
            FileInputStream is = new FileInputStream("dbcp.properties");
            properties.load(is);
        }catch(IOException e){
            e.printStackTrace();
        }

        try{
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //从连接池中获取一个连接
    public static Connection getConnection(){
        Connection connection = null;
        try{
            connection = dataSource.getConnection();
            connection.setAutoCommit(true);
        }catch(SQLException e){
            e.printStackTrace();
        }
        return connection;
    }

    public static void main(String[] args) throws SQLException {

        Connection connection = getConnection();
        Statement statement = connection.createStatement();
        ResultSet result = statement.executeQuery("SELECT ItemName from item_information");
        while(result.next()){
            String itemName = result.getString("ItemName");
            System.out.println(itemName);
        }
        connection.commit();

    }
}